import React, { Component } from "react";
import { Redirect } from "react-router-dom";

import rest from "../../assets/config/rest";

class Authorized extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isLogin: false,
    };
  }

  UNSAFE_componentWillMount() {
    let tokenMap = localStorage.getItem(rest.token);
    if (!tokenMap) {
      return;
    }
    const { token, period } = JSON.parse(tokenMap);
    if (!!token && new Date().getTime() <= period) {
      this.setState({ isLogin: true });
    } else {
      this.setState({ isLogin: false });
    }
  }

  render() {
    const { location, match } = this.props;
    const { isLogin } = this.state;
    if (!isLogin) {
      return <Redirect to="/login" />;
    }
    return match.path === location.pathname ? <Redirect to="/dashboard" /> : "";
  }
}

export default Authorized;
